package com.wy.framework.actions.user;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.ExceptionMapping;
import org.apache.struts2.convention.annotation.ExceptionMappings;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;

import com.wy.component.dataConvert.JsonUtil;
import com.wy.component.properties.PropertiesUtil;
import com.wy.framework.actions.AbstractBaseAction;
import com.wy.framework.constants.RtnCodeConstant;
import com.wy.framework.dao.ErrorSqlException;
import com.wy.framework.exceptions.ServiceException;
import com.wy.framework.pojos.TSysUserinfo;
import com.wy.framework.services.common.FileService;
import com.wy.framework.services.user.UserManageService;

/**
 * 项目名称：openportal
 * 类名称：UserAction
 * 类描述：用户信息管理
 * 创建人：张旭星
 * 创建时间：2015-12-28 下午3:44:24
 * 修改人：张旭星
 * 修改时间：2015-12-28 下午3:44:24
 * 版本信息：@version 1.0
 * Copyright (c) 2015万雍科技（上海）有限公司-版权所有  
 * 修改备注：
 * @version 
 */
@ParentPackage("json")
@Namespace("/manage/user")
@ExceptionMappings({ @ExceptionMapping(exception = "java.lange.RuntimeException", result = "error") })
public class UserAction extends AbstractBaseAction {
	private static final long serialVersionUID = 1L;
	private List<Map> userList;
	private List<Map> userInfo;
	private String jsonRes;
	private List<Map> rows;
	private int page;
	private int total;
	private Map userInfoMap = new HashMap();
	private String iconDetailUrl;
	private String iconDetailUrl1;
	private PropertiesUtil p = new PropertiesUtil();
	public TSysUserinfo tSysUserInfo;
	

	@Autowired
	private UserManageService userManageService;
	
	@Action(value = "addHead", 
			interceptorRefs = { @InterceptorRef("sessionStack") }, 
			results = { @Result(name = "success", type = "json", params = {
			"noCache", "true", "contentType", "text/html", "ignoreHierarchy",
			"false" }) })
	public String addHead()throws ServiceException{
		String dataURL=URLDecoder.decode(ServletActionContext.getRequest().getParameter("dataURL"));
		String userId=ServletActionContext.getRequest().getParameter("userId");
		String headRootPath=this.getClass().getClassLoader().getResource("/").getPath().replace("/WEB-INF/classes", "");
		String headPathBody="";
	      if(StringUtils.isEmpty(userId)){
	    	  try {
					throw new Exception("userId为空!");
		     } catch (Exception e) {
					e.printStackTrace();
			 }
	      }else{
	    	  headPathBody = "/upload/headImg/"+userId+".jpg";
	      }
		rspCode=userManageService.saveHead(dataURL, headRootPath, headPathBody);
		jsonRes=headRootPath+headPathBody;
		return SUCCESS;
	}
	
	/**
	 * Function Name               syncQyhOrgId                                   
	 * @return
	 * @throws ServiceException          		             
	 * @throws ErrorSqlException 
	 * @throws IOException 
	 * @throws FileNotFoundException 
	 * @description 同步企业号部门ID到本地
	 * Modify History:              Date             Programmer       Notes
	 *                            ---------        ---------------  ---------
	 *                      2016-4-27 下午5:42:55           张旭星                     Initial
	 **********************************************************************
	 */
	@Action(value = "syncQyhOrgId", 
			results = { @Result(name = "success", type = "json", params = {
					"noCache", "true", "contentType", "text/html", "ignoreHierarchy",
					"false" }) })
	public String syncQyhOrgId()throws ServiceException, FileNotFoundException, IOException, ErrorSqlException{
		rspCode=userManageService.updateQyhOrgId();
		return SUCCESS;
	}
	 
	/**
	 * 修改用户
	 * Function Name               modify                                   
	 * @return
	 * @throws ServiceException          		             
	 * @description TODO(这里用一句话描述这个方法的作用 – 可选)
	 * Modify History:              Date             Programmer       Notes
	 *                            ---------        ---------------  ---------
	 *                      2016-3-23 上午11:01:09           高振泰                     Initial
	 **********************************************************************
	 */
	@Action(value = "modify", 
			interceptorRefs = { @InterceptorRef("sessionStack") }, 
			results = { @Result(name = "success", type = "json", params = {
			"noCache", "true", "contentType", "text/html", "ignoreHierarchy",
			"false" }) })
	public String modify()throws ServiceException{
		rspCode=userManageService.updateUserInfo(tSysUserInfo);
		return SUCCESS;
	}
	/**
	 * 重置密码
	 * Function Name               resetPwd                                   
	 * @return
	 * @throws ServiceException          		             
	 * @description TODO(这里用一句话描述这个方法的作用 – 可选)
	 * Modify History:              Date             Programmer       Notes
	 *                            ---------        ---------------  ---------
	 *                      2016-3-22 下午4:46:56           高振泰                     Initial
	 **********************************************************************
	 */
	@Action(value = "resetPwd", 
			interceptorRefs = { @InterceptorRef("sessionStack") }, 
			results = { @Result(name = "success", type = "json", params = {
			"noCache", "true", "contentType", "text/html", "ignoreHierarchy",
			"false" }) })
	public String resetPwd()throws ServiceException{
		jsonRes=userManageService.updateResetPwd(ServletActionContext.getRequest().getParameter("userId"));
		return SUCCESS;
	}
	/**
	 * 删除用户
	 * Function Name               delete                                   
	 * @return
	 * @throws ServiceException          		             
	 * @description TODO(这里用一句话描述这个方法的作用 – 可选)
	 * Modify History:              Date             Programmer       Notes
	 *                            ---------        ---------------  ---------
	 *                      2016-3-22 下午4:47:07           高振泰                     Initial
	 **********************************************************************
	 */
	@Action(value = "delete", 
			interceptorRefs = { @InterceptorRef("sessionStack") }, 
			results = { @Result(name = "success", type = "json", params = {
			"noCache", "true", "contentType", "text/html", "ignoreHierarchy",
			"false" }) })
	public String delete()  {
		try {
			rspCode = userManageService.deleteUser(ServletActionContext.getRequest().getParameter("userId"));
		} catch (ServiceException e) {
			e.printStackTrace();
			rspMsg = e.getMessage();
		}
		return SUCCESS;
	}
	/**
	 * 
	 * Function Name               add                                   
	 * @return
	 * @throws ServiceException          		             
	 * @description TODO(这里用一句话描述这个方法的作用 – 可选)
	 * Modify History:              Date             Programmer       Notes
	 *                            ---------        ---------------  ---------
	 *                      2016-3-22 下午4:47:34           高振泰                     Initial
	 **********************************************************************
	 */
	@Action(value = "add", 
			interceptorRefs = { @InterceptorRef("sessionStack") }, 
			results = { @Result(name = "success", type = "json", params = {
			"noCache", "true", "contentType", "text/html", "ignoreHierarchy",
			"false" }) })
	public String add()throws ServiceException{
		rspCode=userManageService.saveUserInfo(tSysUserInfo);
		return SUCCESS;
	}
	/**
	 * 
	 * Function Name               query                                   
	 * @return
	 * @throws ServiceException          		             
	 * @description TODO(后端查询人员列表)
	 * Modify History:              Date             Programmer       Notes
	 *                            ---------        ---------------  ---------
	 *                      2016-3-22 上午10:40:57           高振泰                     Initial
	 **********************************************************************
	 */
	@Action(value = "query", 
			interceptorRefs = { @InterceptorRef("sessionStack") }, 
			results = { @Result(name = "success", type = "json", params = {
			"noCache", "true", "contentType", "text/html", "ignoreHierarchy",
			"false","root","userInfoMap" }) })
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public String query()throws  ServiceException{
		int pageSize = Integer.parseInt(ServletActionContext.getRequest().getParameter("rows"));
		String orgCode = ServletActionContext.getRequest().getParameter("orgCode");
		rows=userManageService.queryUser(orgCode,getPage(),pageSize);
		total=userManageService.queryUserCount(orgCode,null);
		userInfoMap.put("total", total);
		userInfoMap.put("rows", rows);
		return SUCCESS;
	}
	
	
	/**
	 * Function Name               queryUser                                   
	 * @return
	 * @throws ServiceException          		             
	 * @throws ErrorSqlException 
	 * @description TODO(用户查询)
	 * Modify History:              Date             Programmer       Notes
	 *                            ---------        ---------------  ---------
	 *                      2016-1-7 下午1:47:37           朱仕稳                     Initial
	 **********************************************************************
	 */
	@SuppressWarnings("unchecked")
	@Action(value = "queryUser", 
			interceptorRefs = { @InterceptorRef("sessionStack") }, 
			results = { @Result(name = "success", type = "json", params = {
			"noCache", "true", "contentType", "text/html", "ignoreHierarchy",
			"false","root","userInfoMap" }) })
	public String queryUser() throws ServiceException, ErrorSqlException {
		int pageSize = Integer.parseInt(ServletActionContext.getRequest().getParameter("rows"));
		String orgCode = ServletActionContext.getRequest().getParameter("orgCode");
		String searchContent = ServletActionContext.getRequest().getParameter("searchContent");
		try {
			userList=userManageService.queryUserSearch(orgCode,getPage(),pageSize,searchContent);
			total=userManageService.queryUserCount(orgCode,searchContent);
			userInfoMap.put("total", total);
			userInfoMap.put("rows", userList);
		} catch (Exception e) {
			rspCode = RtnCodeConstant.RTN_CODE_UNKNOW_ERROR;
		}
		return SUCCESS;
	}
	@Action(value = "modifyPass", 
			interceptorRefs = { @InterceptorRef("sessionStack") }, 
			results = { @Result(name = "success", type = "json", params = {
			"noCache", "true", "contentType", "text/html", "ignoreHierarchy",
			"false"}) })
	public String modifyPass()throws ServiceException{
		String newPassWord=ServletActionContext.getRequest().getParameter("newPass");
		userManageService.updatePwd(newPassWord);
		return SUCCESS;
	}

	@Action(value = "load", 
			interceptorRefs = { @InterceptorRef("sessionStack") }, 
			results = { @Result(name = "success", type = "json", params = {
			"noCache", "true", "contentType", "text/html", "ignoreHierarchy",
			"false" }) })
	public String load()throws ServiceException{
	   String userId=ServletActionContext.getRequest().getParameter("userId");
		try {
			rows=userManageService.loadUser(userId);
		} catch (ErrorSqlException e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}
	
	@SuppressWarnings("unchecked")
	@Action(value = "getUserInfoById", 
			interceptorRefs = { @InterceptorRef("sessionStack") }, 
			results = { @Result(name = "success", type = "json", params = {
			"noCache", "true", "contentType", "text/html", "ignoreHierarchy",
			"false" }) })
	public String getUserInfoById(){
	   String userId=ServletActionContext.getRequest().getParameter("userId");
		try {
			List list = new ArrayList();
			Map map = new HashMap();
			map.put("userInfo", userManageService.loadUser(userId));
			map.put("allOrg", userManageService.getAllOrgInfo());
			list.add(map);
			rows = list;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}
	
	
	@Action(value = "selfInfoLoad", 
			interceptorRefs = { @InterceptorRef("sessionStack") }, 
			results = { @Result(name = "success", type = "json", params = {
			"noCache", "true", "contentType", "text/html", "ignoreHierarchy",
			"false" }) })
	public String selfInfoLoad()throws Exception{
		 String userId=loginUser().getUserId();
		try {
			rows=userManageService.loadUser(userId);
		} catch (ErrorSqlException e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}
	
	/**
	 * Function Name               judgeUserIdExists                                   
	 * @return
	 * @throws ServiceException          		             
	 * @description TODO(查询工号是否重复 )
	 * Modify History:              Date             Programmer       Notes
	 *                            ---------        ---------------  ---------
	 *                      2016-1-7 上午10:58:56           朱仕稳                     Initial
	 **********************************************************************
	 */
	@Action(value = "judgeUserIdExists", 
			interceptorRefs = { @InterceptorRef("sessionStack") }, 
			results = { @Result(name = "success", type = "json", params = {
			"noCache", "true", "contentType", "text/html", "ignoreHierarchy",
			"false"}) })
	public String judgeUserIdExists()throws ServiceException{
		String userId=ServletActionContext.getRequest().getParameter("userId");
		boolean b=userManageService.getUserIdExists(userId);
		jsonRes = JsonUtil.object2json(b);
		return SUCCESS;
	}
	
	/**
	 * Function Name               judgeMobileExists                                   
	 * @return
	 * @throws ServiceException          		             
	 * @description 验证手机是否存在,true代表已存在
	 * Modify History:              Date             Programmer       Notes
	 *                            ---------        ---------------  ---------
	 *                      2016-5-24 下午1:52:23           张旭星                     Initial
	 **********************************************************************
	 */
	@Action(value = "judgeMobileExists", 
			results = { @Result(name = "success", type = "json", params = {
					"noCache", "true", "contentType", "text/html", "ignoreHierarchy",
			"false"}) })
	public String judgeMobileExists()throws ServiceException{
		String mobile=ServletActionContext.getRequest().getParameter("mobile");
		String userId=ServletActionContext.getRequest().getParameter("userId");
		boolean b=userManageService.judgeMobileExists(mobile,userId);
		jsonRes = JsonUtil.object2json(b);
		return SUCCESS;
	}
	
	
	/**
	 * Function Name               judgePassExists                                   
	 * @return
	 * @throws ServiceException          		             
	 * @description TODO(查询密码是否正确)
	 * Modify History:              Date             Programmer       Notes
	 *                            ---------        ---------------  ---------
	 *                      2016-1-7 上午10:59:50           朱仕稳                     Initial
	 **********************************************************************
	 */
	@Action(value = "judgePassExists", 
			interceptorRefs = { @InterceptorRef("sessionStack") }, 
			results = { @Result(name = "success", type = "json", params = {
			"noCache", "true", "contentType", "text/html", "ignoreHierarchy",
			"false"}) })
    public String judgePassExists()throws ServiceException{
		String password= ServletActionContext.getRequest().getParameter("password");
		boolean b=userManageService.getPassWordExists(password);
		jsonRes = JsonUtil.object2json(b);
		return SUCCESS; 
	}
	
	/**
	 * Function Name               info                                   
	 * @return
	 * @throws IOException 
	 * @throws FileNotFoundException 
	 * @throws ServiceException
	 * @throws ErrorSqlException          		             
	 * @description 查用户信息
	 * Modify History:              Date             Programmer       Notes
	 *                            ---------        ---------------  ---------
	 *                      2016-1-7 下午5:26:38           朱仕稳                     Initial
	 **********************************************************************
	 */
	@Action(value = "info", 
			interceptorRefs = { @InterceptorRef("sessionStack") }, 
			results = { @Result(name = "success", type = "json", params = {
			"noCache", "true", "contentType", "text/html", "ignoreHierarchy",
			"false"}) })
	public String info() throws FileNotFoundException, IOException {
		String userId= ServletActionContext.getRequest().getParameter("userId");
		try {
			rows = userManageService.queryUserInfo(userId);
			iconDetailUrl = p.getAppProperties("iconDetailUrl");
			iconDetailUrl1 = p.getAppProperties("iconDetailUrl1");
		} catch (ErrorSqlException e) {
			e.printStackTrace();
		}
		return SUCCESS; 
	}
	

	/**
	 * Function Name               registQyh                                   
	 * @return
	 * @throws ServiceException
	 * @throws FileNotFoundException
	 * @throws IOException
	 * @throws ErrorSqlException          		             
	 * @description 企业号企业小助手3x5菜单注册外部人员
	 * Modify History:              Date             Programmer       Notes
	 *                            ---------        ---------------  ---------
	 *                      2016-5-23 下午3:36:56           张旭星                     Initial
	 **********************************************************************
	 */
	@Action(value = "registQyhOutside", 
			results = { @Result(name = "success", type = "json", params = {
					"noCache", "true", "contentType", "text/html", "ignoreHierarchy",
			"false" }) })
	public String registQyhOutside() throws ServiceException, FileNotFoundException, IOException, ErrorSqlException{
		String userName = ServletActionContext.getRequest().getParameter("userName");
		String userId = ServletActionContext.getRequest().getParameter("userId");
		String email = ServletActionContext.getRequest().getParameter("email");
		String mobile = ServletActionContext.getRequest().getParameter("mobile");
		String orgCode = ServletActionContext.getRequest().getParameter("orgCode");
		String type = ServletActionContext.getRequest().getParameter("type");
		rspCode = userManageService.saveQyhOutside(userId,userName,mobile,email,orgCode,type);
		return SUCCESS;
	}
	
	
	
	/**
	 * APP端修改用户信息
	 * Function Name               modifyUser                                   
	 * @return
	 * @throws IllegalAccessException
	 * @throws InvocationTargetException
	 * @throws ErrorSqlException
	 * @throws NoSuchMethodException          		             
	 * @description TODO(APP端修改用户信息)
	 * Modify History:              Date             Programmer       Notes
	 *                            ---------        ---------------  ---------
	 *                      2016-3-18 上午11:43:36           高振泰                     Initial
	 **********************************************************************
	 */
	@Action(value = "modifyUser", results = { @Result(name = "success", location = "/jsps/apiEncrypt.jsp") })
	public String modifyUser() throws IllegalAccessException, InvocationTargetException,ErrorSqlException, NoSuchMethodException{
		String userId= ServletActionContext.getRequest().getParameter("userId");
		String category= ServletActionContext.getRequest().getParameter("category");
		String value= ServletActionContext.getRequest().getParameter("value");
		rspCode=userManageService.modifyUserForApp(userId, category, value);
		return SUCCESS; 
	}
	
	 private String fileName;
	 private File file;
	 private String fileDiskName;
	 private String fileSize;
	 
	 @Autowired
	 private FileService fileService;
	 private  String headPortraitUpload() throws ServiceException {
		 //		 http://huodongzhinan.com/fileUploadMportal

	    	MultiPartRequestWrapper req = (MultiPartRequestWrapper) ServletActionContext.getRequest();
	    	// 文件名
	    	fileName = req.getFileNames("file")[0];
	    	fileName = fileName.replaceAll("%", "％").replaceAll("'", "‘").replace(" ", "").replace(" ", "");
	    	// 允许的文件类型
	    	String allowedType = req.getParameter("allowedType");
	    	// 文件的业务类型(如附件、模板)
	    	String type = req.getParameter("type");
	    	//允许大小
	    	String allowedSize = req.getParameter("allowedSize");
	    	file = req.getFiles("file")[0];
	    	// 物理文件名\文件大小将返回给前端
	    	fileDiskName = fileService.getUniqueName(fileName);
	    	
	    	long size = file.length();
	    	fileSize = new DecimalFormat("0.00KB").format(size / 1024.0);
	    	long maxSize;
	    	if(StringUtils.isNotEmpty(allowedSize))
	    		maxSize = Integer.parseInt(allowedSize) * 1024;//KB转为Byte
			else
				maxSize = new BigDecimal(fileService.getMaxSize()).longValue();
	    	if (size > maxSize) {
	    		rspCode = RtnCodeConstant.RTN_CODE_FILE_UPLOAD_MAX_SIZE_ERROR;
	    		rspMsg = msgSourceAdapter.getMessage(RtnCodeConstant.RTN_CODE_FILE_UPLOAD_MAX_SIZE_ERROR, new String[] { String.valueOf(maxSize/1024)+"KB" });
//	    		logger.error("文件上传失败:文件大小超限【" + String.valueOf(maxSize) + "】");
	    		file.delete();
	    		return SUCCESS;
	    	}
	    	
	    	// 空文件检查
	    	if (size == 0) {
	    		rspCode = RtnCodeConstant.RTN_CODE_FILE_EMPTY_ERROR;
	    		file.delete();
	    		return SUCCESS;
	    	}
	    	
			// 将文件拷贝到配置的目录
			String newFile = fileService.getFolder() + fileDiskName;
			try {
			    FileUtils.copyFile(file, new File(newFile));
			    
			} catch (IOException e) {
//			    logger.error("拷贝文件失败 from:{},to{}", file.getAbsolutePath(), newFile);
//			    logger.error(e.getMessage());
			    rspCode = RtnCodeConstant.RTN_CODE_FILE_UPLOAD_ERROR;
			}
//			logger.info("上传文件名:{},文件大小:{}", fileName, fileSize);
			JSONObject j = new JSONObject();
			StringBuffer url = req.getRequestURL();  
			String tempContextUrl = url.delete(url.length() - req.getRequestURI().length(), url.length()).append("/").toString();  
			j.put("path", tempContextUrl +"/upload/"+fileDiskName);
			jsonRes = j.toString();
			return "success";
		} 

	public int getTotal() {
		return total;
	}


	public Map getUserInfoMap() {
		return userInfoMap;
	}



	public void setUserInfoMap(Map userInfoMap) {
		this.userInfoMap = userInfoMap;
	}

	public List<Map> getRows() {
		return rows;
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}


	public List<Map> getUserList() {
		return userList;
	}

	public List<Map> getUserInfo() {
		return userInfo;
	}

	public void setUserInfo(List<Map> userInfo) {
		this.userInfo = userInfo;
	}

	public String getJsonRes() {
		return jsonRes;
	}

	public void setJsonRes(String jsonRes) {
		this.jsonRes = jsonRes;
	}

	public TSysUserinfo gettSysUserInfo() {
		return tSysUserInfo;
	}

	public void settSysUserInfo(TSysUserinfo tSysUserInfo) {
		this.tSysUserInfo = tSysUserInfo;
	}


	public String getIconDetailUrl() {
		return iconDetailUrl;
	}


	public String getIconDetailUrl1() {
		return iconDetailUrl1;
	}

}
